<?php

namespace app\modules\Finance\controllers;

use Yii;
use app\modules\Finance\models\Invoice;
use app\modules\Finance\models\InvoiceSearch;
use app\modules\Finance\models\InvoiceCompany;
use app\modules\Finance\models\InvoiceOrder;
use app\modules\Finance\models\Finance;
use app\modules\Order\models\Order;
use app\modules\Product\models\Product;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;
use yii\data\ArrayDataProvider;

/**
 * InvoiceController implements the CRUD actions for Invoice model.
 */
class InvoiceController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all Invoice models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new InvoiceSearch();
        $dataProvider = $searchModel->search_all(Yii::$app->request->queryParams);

        $min_price = $max_price = 0;
        if(isset(Yii::$app->request->queryParams['InvoiceSearch']['min_price'])){
            $min_price = Yii::$app->request->queryParams['InvoiceSearch']['min_price'];
        }
        if(isset(Yii::$app->request->queryParams['InvoiceSearch']['max_price'])){
            $max_price = Yii::$app->request->queryParams['InvoiceSearch']['max_price'];
        }

        $all_model = [];
        
        if($dataProvider){
            foreach($dataProvider as $model){
                if($min_price == 0 && $max_price == 0){
                    $all_model[] = $model;
                }else if($min_price != 0 && $max_price == 0){
                    if($model->orderPrice >= $min_price){
                        $all_model[] = $model;
                    }
                }else if($min_price == 0 && $max_price != 0){
                    if($model->orderPrice <= $max_price){
                        $all_model[] = $model;
                    }
                }else if($min_price !=0 && $max_price !=0){

                    if($model->orderPrice >= $min_price && $model->orderPrice <= $max_price){
                        $all_model[] = $model;
                    }
                }
            }
        }

        //sort 创建时间排序 
        $sort = 0;
        if(isset(Yii::$app->request->queryParams['InvoiceSearch']['sort'])){
            $sort = Yii::$app->request->queryParams['InvoiceSearch']['sort'];
        }

        if($sort == 1){
            $sort = SORT_ASC;
        }else{
            $sort = SORT_DESC;
        }
        
        $provider = new ArrayDataProvider([
              'allModels' => $all_model,
              'sort' => [
                    'attributes' => ['created_at'],
                    'defaultOrder' => [
                        'created_at' => $sort,
                    ],
               ],
              'pagination' => [
                  'pageSize' => 20,
                  'defaultPageSize'=>20,
              ],
        ]);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $provider,
            'min_price' => $min_price,
            'max_price' => $max_price
        ]);
    }

    /**
     * Displays a single Invoice model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Invoice model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Invoice();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'finance_id' => $finance_id,
            ]);
        }
    }
    //
    public function actionGetProduct(){
        $out = [];
        if(isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            if ($parents != null) {
                $cruise_id = $parents[0];

                $time = date("Y-m-d",strtotime("-3 month"));
                $arr = Product::find()->where(['>=','go_time', $time])->andWhere(['status'=>1,'cruise_id'=>$cruise_id])->all();
                if($arr){
                    foreach($arr as $key=>$v){
                        $out[$key]['id'] = $v->id;
                        $out[$key]['name'] = $v->code;
                    }
                }

                echo json_encode(['output'=>$out, 'selected'=>'']);
                return;
            }
        }
        echo json_encode(['output'=>'', 'selected'=>'']);
    }

    //创建发票单
    public function actionCreateNew($finance_id)
    {
        $this->layout = "//empty";

        $model = new Invoice();

        $finance = Finance::findOne($finance_id);
         
        if ($model->load(Yii::$app->request->post())) {
           
            if($model->save()){
                $data = Yii::$app->request->post();
                $in_data = isset($data['InvoiceOrder'])?$data['InvoiceOrder']:'';
                if($in_data){
                     foreach($in_data as $invoice){
                        if($invoice['price'] > 0){
                             $order = Order::findOne($invoice['order_id']);
                             $InOrder = new InvoiceOrder();
                             $InOrder->order_id = $order->id;
                             $InOrder->order_code = $order->code;
                             $InOrder->product_id = $order->product_id;
                             $InOrder->price = isset($invoice['price'])?$invoice['price']:0;
                             $InOrder->invoice_id = $model->id;
                             $InOrder->finance_id = $model->finance_id;
                             $InOrder->save();
                        }
                     }
                     return $this->redirect(Yii::$app->request->getReferrer());
                }
                
            }

            
            exit();    
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model->finance_id = $finance_id;
            $model->status = 1;
            $model->type = $finance->type;
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    //移除订单
    public function actionRemoveOrder($id)
    {
        $model = InvoiceOrder::findOne($id);
        
        if($model){
            
            if($model->invoice->status == 3){ //审核通过
                 return $this->redirect(Yii::$app->request->getReferrer());
            }    

            $model->delete();

            return $this->redirect(Yii::$app->request->getReferrer());
        }
    }


    public function actionSuggest($q = null){//{{{
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $out = $arr = [];

        if($q){
            $data = InvoiceCompany::find()->where(['like', 'company', $q])->all();
            if($data){
                foreach($data as $key=>$model){
                    $arr[$key] = ['id'=>$model->id, 'text'=>sprintf("%s (%s | %s)", $model->company, $model->tax, $model->bank_account) ]; 
                }
            }
        }

        if($arr){
            $out['results'] = $arr;
            return $out;
        }else{
            $arr[] = ['id'=>'' , 'text'=>'无结果'];    
            $out['results'] = $arr;
            return $out;
            //return NULL; 
        }
    }//}}}

    public function actionFindCompany($id = null){//{{{
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if($id){
            $model = InvoiceCompany::findOne($id);
            return $model;
        }
    }//}}}

    /**
     * Updates an existing Invoice model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $this->layout = "//empty";
        $model = $this->findModel($id);
        if($model->status == 3){
            echo "发票已审核通过!";
            return false;
        }

        if ($model->load(Yii::$app->request->post())) {
            //修改状态为提交申请
            $model->status = 1;
            if($model->save()){
                $data = Yii::$app->request->post();
                $in_data = isset($data['InvoiceOrder'])?$data['InvoiceOrder']:'';
                if($in_data){
                     foreach($in_data as $invoice){
                        if($invoice['price'] > 0){
                             $order = Order::findOne($invoice['order_id']);
                             $InOrder = InvoiceOrder::find()->where(['order_id'=>$invoice['order_id'],'invoice_id'=>$model->id])->one();
                             if(!$InOrder){
                                 $InOrder = new InvoiceOrder();
                             }
                             $InOrder->order_id = $order->id;
                             $InOrder->order_code = $order->code;
                             $InOrder->product_id = $order->product_id;
                             $InOrder->price = isset($invoice['price'])?$invoice['price']:0;
                             $InOrder->invoice_id = $model->id;
                             $InOrder->finance_id = $model->finance_id;
                             $InOrder->save();
                        }
                     }
                     return $this->redirect(Yii::$app->request->getReferrer());
                }
                
            }
            exit();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }


    // 修改
    public function actionEdit($id){ //{{{

        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $model = $this->findModel($id);

        $params = Yii::$app->request->get();

        if ($model->load($params) &&  $model->save()) {

            //  return $this->redirect(['view', 'id' => $model->id]);

            return ['output'=>$model->code, 'message'=>"" ];
        }
    }//}}}
     public function actionCheckStatus()
     {
        $id = Yii::$app->request->post('id');
        $status  = Yii::$app->request->post('status');

        if ($id && $status) {

            $invoice = Invoice::findOne($id);
            $invoice->status = $status;
            // 记录审批记录
            if($invoice->save()){
                return $this->redirect(Yii::$app->request->getReferrer());
            }else{
               print_r($invoice->errors);  
            }
            
        }
     }


    /**
     * Deletes an existing Invoice model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Invoice model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Invoice the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Invoice::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
